package org.microsites.domain.dao.eod;

import java.util.ArrayList;
import java.util.List;

import net.lemnik.eodsql.BaseQuery;
import net.lemnik.eodsql.DataSet;
import net.lemnik.eodsql.GeneratedKeys;
import net.lemnik.eodsql.Select;
import net.lemnik.eodsql.Update;

import org.microsites.domain.dao.FileSetDAO;
import org.microsites.domain.model.FileSet;
import org.microsites.util.EodDaoSupport;

public class FileSetDAOImpl extends EodDaoSupport implements FileSetDAO {
	private Query query;
	
	@Override
	public void create(FileSet entity) {
		entity.setId(getQuery().create(entity));
	}

	@Override
	public void delete(Long id) {
		getQuery().delete(id);
	}

	@Override
	public List<FileSet> list() {
		return getQuery().list();
	}

	@Override
	public List<FileSet> sublist(Long id) {
		return id == null ? new ArrayList<FileSet>() : getQuery().sublist(id);
	}

	@Override
	public FileSet load(Long id) {
		return getQuery().load(id);
	}

	@Override
	public void update(FileSet entity) {
		getQuery().update(entity);
	}
	
	public Query getQuery() {
		return query == null ? query = super.getQuery(Query.class) : query;
	}

	@Override
	public List<FileSet> sublistInProject(Long project) {
		return getQuery().sublistInProject(project);
	}

	@Override
	public List<String> autocomplete(String column, String pattern) {
		return super.select(String.class, "SELECT " + column + " FROM FileSet WHERE " + column + " LIKE ?1 GROUP BY " + column, '%' + pattern + '%');
	}

	static interface Query extends BaseQuery {
		@Update(sql = "INSERT INTO FileSet (name,description,path,server) VALUES (?{1.name},?{1.description},?{1.path},?{1.server})",
                keys = GeneratedKeys.RETURNED_KEYS_FIRST_COLUMN)
		public Long create(FileSet p);
		
		@Update(sql = "DELETE FROM FileSet WHERE id=?1")
		public void delete(Long id);
		
		@Select(sql = "SELECT * FROM FileSet")
		public DataSet<FileSet> list();
		
		@Select(sql = "SELECT * FROM FileSet WHERE server=?1")
		public DataSet<FileSet> sublist(Long id);
		
		@Select(sql = "SELECT fs.* FROM FileSet fs INNER JOIN Project_FileSet pfs ON fs.id=pfs.fileset WHERE pfs.project=?1")
		public List<FileSet> sublistInProject(Long project);

		@Select(sql = "SELECT * FROM FileSet WHERE id=?1")
		public FileSet load(Long id);
		
		@Update(sql = "UPDATE FileSet SET name=?{1.name},description=?{1.description},path=?{1.path},server=?{1.server} WHERE id=?{1.id}")
		public void update(FileSet p);
		
	}

}
